package com.hursing.tractor.baseview;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Paint.FontMetricsInt;

public class UITextButton extends UIButton {

	protected static final Paint sTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
	public static final void paintTextSize(float size) {
		sTextPaint.setTextSize(size);
		sTextPaint.setTextAlign(Paint.Align.CENTER);
	}
	
	private String mText;
	private int mTextBaseline;
	protected Paint mPaint;

	@Override
	public UITextButton toTextButton() { return this; }
	
	@Override
	public UIView text(String text) {
		mText = text;
		mPaint = sTextPaint;
		invalidate();
		return this;
	}
	
	@Override
	public String text() {
		return mText;
	}
	
	@Override
	public int measureWidth() {
		FontMetricsInt fmi = mPaint.getFontMetricsInt();
		// 计算左右两边的文字margin = button高度-文字高度
		return (int)Math.ceil(mPaint.measureText(mText) + 2 * (mFrame.height() - (fmi.descent - fmi.ascent)));
	}
	
	@Override
	public UIView paint(Paint paint) {
		mPaint = paint;
		return this;
	}
	
	@Override
	public Paint paint() {
		return mPaint;
	}
	
	@Override
	public UIView frame(Rect rect) {
		super.frame(rect);
		FontMetricsInt fmi = mPaint.getFontMetricsInt();
		mTextBaseline = (mFrame.bottom - mFrame.top - fmi.bottom + fmi.top) / 2 + mFrame.top - fmi.top;
		return this;
	}

	@Override
	protected void doDraw (Canvas canvas) {
		super.doDraw(canvas);
		canvas.drawText(mText, mFrame.centerX(), mTextBaseline, mPaint);
	}
}
